package com.wave2.shadow.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import com.wave2.shadow.dao.RegistrationDao;
import com.wave2.shadow.exceptions.UserAlreadyExists;
import com.wave2.shadow.model.JoinForm;

@Service("jgaRegistrationService")
@Transactional
@TransactionConfiguration(transactionManager="transactionManager")
public class JGARegistrationService {

	@Autowired
	private RegistrationDao registrationDao;
	
	/*
	 * Used ONLY for JUnit testing. This allows us to insert a mocked DAO into the service instead of using the normally autowired bean from spring.
	 */
	public void setRegistrationDao(RegistrationDao registrationDao) {
		this.registrationDao = registrationDao;
	}

	/* 
	 * Calls the DAO object to add the user to the database.
	 * The DAO object can exception so we need to catch each exception and throw it up to the Controller as well as log it. 
	*/
	public boolean createUser(JoinForm user) throws Exception, UserAlreadyExists{
		//TODO: Add exception handling.
		
		try{
			registrationDao.addUser(user);
			System.out.println("User Data added.");
			sendEmail();			
		}
		catch(UserAlreadyExists e){
			System.out.println("User Data NOT added." + e.getMessage());
			throw e;
		}
		catch(Exception e){
			System.out.println("User Data NOT added." + e.getMessage());
			throw e;			
		}
		
		// Added return for Mocking ONLY. EasyMock Requires a return value.
		return true;
	}
	
	/*
	 * Method stub for sending a confirmation email to the user. We saw no value in implementing this to learn Spring/Hibernate.
	 */
	public void sendEmail()
	{
		System.out.println("Email sent.");
	}
}
